/**
 * 使用 zustand + immer 管理任务列表状态
 * - 支持分类管理：工作 / 学习 / 生活 / 专注
 * - 支持任务增删改查
 * - 支持专注模式与番茄钟统计
 */
import { TASK_STATUS, TASK_TYPE } from '@/enums'
import { TaskItem } from '@/types'
import { Modal } from 'antd'
import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
import { enableMapSet } from 'immer'
import { prioritySortOptions } from '@/pages/Tasks/config'
enableMapSet() // 让 immer 支持 Map 和 Set

interface TaskState {
  /** 任务列表 */
  tasks: TaskItem[]
  /** 是否正在加载 */
  loading: boolean

  // UI 状态
  showNewTaskForm: boolean
  selectedTypes: Set<TASK_TYPE | 'all'>
  prioritySort: (typeof prioritySortOptions)[number]

  // computed
  renderTasks: () => {
    activeTasks: TaskItem[]
    completedTasks: TaskItem[]
  }

  // 获取任务统计信息
  getTaskStats: () => {
    total: number
    active: number
    completed: number
    byType: Record<string, number>
    byPriority: Record<string, number>
  }

  /** 初始化加载任务 */
  loadTasks: () => Promise<void>
  /** 添加任务 */
  addTask: (task: TaskItem) => Promise<void>
  /** 更新任务 */
  updateTask: (id: string, partial: Partial<TaskItem>) => Promise<void>
  /** 删除任务 */
  deleteTask: (id: string) => Promise<void>
  /** 清空已完成任务 */
  clearCompletedTasks: () => Promise<void>
  /** 设置是否显示TaskForm */
  onShowNewTaskForm: (flag: boolean) => void
  /** 优先级排序 */
  onPrioritySort: () => void
  /** 类型选择 */
  onTypeSelect: (type: TASK_TYPE | 'all') => void
}

// immer 中间件让我们可以在不直接修改状态的情况下编写更简洁的更新逻辑
export const useTaskStore = create<TaskState>()(
  immer((set, get) => ({
    tasks: [],
    loading: false,

    showNewTaskForm: false,
    selectedTypes: new Set<TASK_TYPE | 'all'>(['all']),
    prioritySort: prioritySortOptions[0],

    // 计算属性：区分完成、未完成任务
    renderTasks() {
      const { tasks, selectedTypes, prioritySort } = get()
      const sortedTasks = [...tasks].sort((a, b) => {
        if (prioritySort === 'asc') return a.priority - b.priority
        if (prioritySort === 'desc') return b.priority - a.priority
        return 0
      })

      const activeTasks: TaskItem[] = []
      const completedTasks: TaskItem[] = []
      sortedTasks.forEach((task) => {
        if (selectedTypes.has('all') || selectedTypes.has(task.type)) {
          // 计算每个任务的完成状态
          const isCompleted = task.status === TASK_STATUS.COMPLETED
          if (isCompleted) {
            completedTasks.push(task)
          } else {
            activeTasks.push(task)
          }
        }
      })
      return { activeTasks, completedTasks }
    },

    // 获取任务统计信息
    getTaskStats() {
      const { tasks } = get()
      const stats = {
        total: tasks.length,
        active: 0,
        completed: 0,
        byType: {} as Record<string, number>,
        byPriority: {} as Record<string, number>
      }

      tasks.forEach((task) => {
        // 统计完成状态
        if (task.status === TASK_STATUS.COMPLETED) {
          stats.completed++
        } else {
          stats.active++
        }

        // 按类型统计
        stats.byType[task.type] = (stats.byType[task.type] || 0) + 1

        // 按优先级统计
        const priorityKey = task.priority.toString()
        stats.byPriority[priorityKey] = (stats.byPriority[priorityKey] || 0) + 1
      })

      return stats
    },

    /** 初始化加载 */
    loadTasks: async () => {
      set((state) => {
        state.loading = true
      })

      try {
        const tasks = await window.taskApi.getAll()
        set((state) => {
          state.tasks = tasks ?? []
          state.loading = false
        })
      } catch (error) {
        console.error('加载任务失败:', error)
        set((state) => {
          state.loading = false
        })
      }
    },

    /** 添加任务 */
    addTask: async (task: TaskItem) => {
      try {
        const newTask: TaskItem = {
          ...task,
          id: task.id || Date.now().toString(),
          createdAt: task.createdAt || new Date(),
          updatedAt: new Date(),
          progress: task.progress || 0,
          status: TASK_STATUS.NOT_STARTED
        }

        set((state) => {
          state.tasks.unshift(newTask)
        })
        await window.taskApi.add(newTask)
      } catch (error) {
        console.error('添加任务失败:', error)
      }
    },

    /** 更新任务 */
    updateTask: async (id, partial) => {
      try {
        let updatedTask: TaskItem | null = null

        set((state) => {
          const update = (tasks: TaskItem[]): boolean => {
            for (const t of tasks) {
              if (t.id === id) {
                Object.assign(t, partial)
                t.updatedAt = new Date()
                updatedTask = { ...t }
                return true
              }
              if (t.children && update(t.children)) return true
            }
            return false
          }
          update(state.tasks)
        })

        if (updatedTask) {
          await window.taskApi.update(updatedTask)
        }
      } catch (error) {
        console.error('更新任务失败:', error)
        get().loadTasks()
      }
    },

    /** 删除任务 */
    deleteTask: async (id) => {
      Modal.confirm({
        title: '删除任务',
        content: '确定要删除此任务吗？',
        okText: '确定',
        cancelText: '取消',
        onOk: async () => {
          try {
            set((state) => {
              const remove = (tasks: TaskItem[]): TaskItem[] =>
                tasks.filter((t) => {
                  if (t.id === id) return false
                  if (t.children) t.children = remove(t.children)
                  return true
                })
              state.tasks = remove(state.tasks)
            })

            await window.taskApi.delete(id)
          } catch (error) {
            console.error('删除任务失败:', error)
            get().loadTasks()
          }
        }
      })
    },
    /** 设置是否显示TaskForm */
    onShowNewTaskForm: (flag: boolean) => {
      set((state) => {
        state.showNewTaskForm = flag
      })
    },

    /** 优先级排序 */
    onPrioritySort: () => {
      set((state) => {
        const index = prioritySortOptions.findIndex((opt) => opt === state.prioritySort)
        state.prioritySort = prioritySortOptions[(index + 1) % prioritySortOptions.length]
      })
    },

    /** 清空已完成任务 */
    clearCompletedTasks: async () => {
      try {
        // 提示用户
        Modal.confirm({
          title: '清空已完成任务',
          content: '确定要清空已完成任务吗？',
          okText: '确定',
          cancelText: '取消',
          okButtonProps: {
            danger: true
          },
          onOk: async () => {
            // 删除已完成任务
            const completedTaskIds = get()
              .tasks.filter((task) => task.status === TASK_STATUS.COMPLETED)
              .map((task) => task.id)

            for (const id of completedTaskIds) {
              await window.taskApi.delete(id)
            }

            set((state) => {
              state.tasks = state.tasks.filter((task) => task.status !== TASK_STATUS.COMPLETED)
            })
          }
        })
      } catch (error) {
        console.error('清空已完成任务失败:', error)
        get().loadTasks()
      }
    },

    /** 类型选择 */
    onTypeSelect: (type: TASK_TYPE | 'all') => {
      set((state) => {
        const { selectedTypes } = state
        if (type === 'all') {
          if (selectedTypes.has('all')) return
          state.selectedTypes = new Set<TASK_TYPE | 'all'>(['all'])
        } else {
          selectedTypes.has('all') && selectedTypes.delete('all')
          selectedTypes.has(type) ? selectedTypes.delete(type) : selectedTypes.add(type)
        }
      })
    }
  }))
)
